<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="生产线名称" prop="lineName">
        <el-input
          v-model="queryParams.lineName"
          placeholder="请输入生产线名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="生产线编号" prop="lineCode">
        <el-input
          v-model="queryParams.lineCode"
          placeholder="请输入生产线编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属车间" prop="workshopId">
        <el-select v-model="queryParams.workshopId" placeholder="请选择所属车间" clearable>
          <el-option
            v-for="item in workshopOptions"
            :key="item.workshopId"
            :label="item.workshopName"
            :value="item.workshopId"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="生产线状态" prop="lineStatus">
        <el-select v-model="queryParams.lineStatus" placeholder="请选择生产线状态" clearable>
          <el-option
            v-for="dict in production_line_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="生产线类型" prop="lineType">
        <el-select v-model="queryParams.lineType" placeholder="请选择生产线类型" clearable>
          <el-option
            v-for="dict in production_line_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设计产能" prop="capacity">
        <el-input
          v-model="queryParams.capacity"
          placeholder="请输入设计产能"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['bdm:line:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['bdm:line:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['bdm:line:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['bdm:line:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="lineList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="生产线ID" align="center" prop="lineId" />
      <el-table-column label="生产线名称" align="center" prop="lineName" />
      <el-table-column label="生产线编号" align="center" prop="lineCode" />
      <el-table-column label="所属车间" align="center" prop="workshopId">
        <template #default="scope">
          <span>{{ getWorkshopName(scope.row.workshopId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生产线状态" align="center" prop="lineStatus">
        <template #default="scope">
          <dict-tag :options="production_line_status" :value="scope.row.lineStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="生产线类型" align="center" prop="lineType">
        <template #default="scope">
          <dict-tag :options="production_line_type" :value="scope.row.lineType"/>
        </template>
      </el-table-column>
      <el-table-column label="设计产能" align="center" prop="capacity" />
      <el-table-column label="设备数量" align="center" prop="equipmentCount" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['bdm:line:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['bdm:line:remove']" v-if="scope.row.equipmentCount === 0">删除</el-button>
          <el-button link type="primary" icon="Plus" @click="handleAddEquipment(scope.row)">添加设备</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改生产线管理对话框 -->
    <!-- 修改对话框宽度为1200px -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
  <el-tabs type="border-card">
    <el-tab-pane label="基本信息">
      <el-form ref="lineRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生产线名称" prop="lineName">
              <el-input v-model="form.lineName" placeholder="请输入生产线名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产线编号" prop="lineCode">
              <el-input v-model="form.lineCode" placeholder="请输入生产线编号" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属车间" prop="workshopId">
              <el-select 
                v-model="form.workshopId" 
                placeholder="请选择所属车间"
                style="width: 100%"
              >
                <el-option
                  v-for="item in workshopOptions"
                  :key="item.workshopId"
                  :label="item.workshopName"
                  :value="item.workshopId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产线状态" prop="lineStatus">
              <el-select 
                v-model="form.lineStatus" 
                placeholder="请选择生产线状态"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in production_line_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产线类型" prop="lineType">
              <el-select 
                v-model="form.lineType" 
                placeholder="请选择生产线类型"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in production_line_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设计产能" prop="capacity">
              <el-input v-model="form.capacity" placeholder="请输入设计产能" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-tab-pane>
    
    <el-tab-pane label="设备列表">
      <el-table 
        :data="equipmentList" 
        v-loading="equipmentLoading" 
        height="400"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column label="设备ID" prop="equipmentId" width="100" align="center" />
        <el-table-column label="设备名称" prop="equipmentName" align="center" />
        <el-table-column label="设备编号" prop="equipmentCode" align="center" />
        <el-table-column label="设备类型" prop="equipmentType" align="center">
          <template #default="scope">
            <dict-tag :options="equipment_type" :value="scope.row.equipmentType"/>
          </template>
        </el-table-column>
        <el-table-column label="设备状态" prop="status" align="center">
          <template #default="scope">
            <dict-tag :options="equipment_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
      </el-table>
      <pagination
    v-show="equipmentTotal>0"
    :total="equipmentTotal"
    v-model:page="equipmentQueryParams.pageNum"
    v-model:limit="equipmentQueryParams.pageSize"
    @pagination="handleEquipmentPagination"
  />
    </el-tab-pane>
  </el-tabs>

  <template #footer>
    <div class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </template>
</el-dialog>

    <!-- 设备选择对话框 -->
    <el-dialog 
      title="选择设备" 
      v-model="equipmentSelectOpen" 
      width="1000px" 
      append-to-body
    >
      <el-form :model="equipmentSelectQueryParams" ref="equipmentSelectQueryRef" :inline="true" label-width="68px">
        <el-form-item label="设备名称" prop="equipmentName">
          <el-input
            v-model="equipmentSelectQueryParams.equipmentName"
            placeholder="请输入设备名称"
            clearable
            @keyup.enter="handleEquipmentSelectQuery"
          />
        </el-form-item>
        <el-form-item label="设备编号" prop="equipmentCode">
          <el-input
            v-model="equipmentSelectQueryParams.equipmentCode"
            placeholder="请输入设备编号"
            clearable
            @keyup.enter="handleEquipmentSelectQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleEquipmentSelectQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetEquipmentSelectQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="equipmentSelectLoading" :data="availableEquipmentList" border stripe>
        <el-table-column label="设备ID" align="center" prop="equipmentId" />
        <el-table-column label="设备名称" align="center" prop="equipmentName" />
        <el-table-column label="设备编号" align="center" prop="equipmentCode" />
        <el-table-column label="设备类型" align="center" prop="equipmentType">
          <template #default="scope">
            <dict-tag :options="equipment_type" :value="scope.row.equipmentType"/>
          </template>
        </el-table-column>
        <el-table-column label="设备状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="equipment_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="分配状态" align="center">
          <template #default="scope">
            <el-tag type="success" v-if="!scope.row.lineId || scope.row.lineId === 0 || scope.row.lineId === ''">未分配</el-tag>
            <el-tag type="info" v-else>已分配</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120">
          <template #default="scope">
            <el-button 
              type="primary" 
              link 
              @click="confirmAddEquipment(scope.row)"
              v-if="!scope.row.lineId || scope.row.lineId === 0 || scope.row.lineId === ''"
            >选择</el-button>
            <span v-else>已分配</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="equipmentSelectTotal>0"
        :total="equipmentSelectTotal"
        v-model:page="equipmentSelectQueryParams.pageNum"
        v-model:limit="equipmentSelectQueryParams.pageSize"
        @pagination="getAvailableEquipmentList"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="equipmentSelectOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Line">
import { listLine, getLine, delLine, addLine, updateLine, listWorkshop } from "@/api/bdm/line";
import { listEquipment, updateEquipment } from "@/api/dm/equipment"; // 新增导入设备API
import { generateProductionLineCode } from "@/utils/generator";

const { proxy } = getCurrentInstance();
const { production_line_type, production_line_status, equipment_type, equipment_status } = 
  proxy.useDict('production_line_type', 'production_line_status', 'equipment_type', 'equipment_status'); // 添加设备字典

// 新增设备相关状态
const equipmentList = ref([]);
const equipmentLoading = ref(false);
const equipmentTotal = ref(0); // 新增设备总数
const equipmentQueryParams = ref({ // 新增设备查询参数
  pageNum: 1,
  pageSize: 10,
  lineId: null
});

const lineList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const workshopOptions = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    lineName: null,
    lineCode: null,
    workshopId: null,
    lineStatus: null,
    lineType: null,
    capacity: null,
  },
  rules: {
    lineName: [
      { required: true, message: "生产线名称不能为空", trigger: "blur" }
    ],
    lineCode: [
      { required: true, message: "生产线编号不能为空", trigger: "blur" }
    ],
  }
});


const { queryParams, form, rules } = toRefs(data);



// 根据车间ID获取车间名称
function getWorkshopName(workshopId) {
  const workshop = workshopOptions.value.find(item => item.workshopId === workshopId);
  return workshop ? workshop.workshopName : workshopId;
}

/** 查询生产线管理列表 */
function getList() {
  loading.value = true;
  listLine(queryParams.value).then(response => {
    // 获取每个生产线的设备数量
    const lines = response.rows;
    Promise.all(lines.map(line => 
      listEquipment({ lineId: line.lineId }).then(res => ({
        ...line,
        equipmentCount: res.total || 0
      }))
    )).then(linesWithCount => {
      lineList.value = linesWithCount;
      total.value = response.total;
      loading.value = false;
    });
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    lineId: null,
    lineName: null,
    lineCode: null,
    workshopId: null,
    lineStatus: null,
    lineType: null,
    capacity: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("lineRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.lineId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  // 自动生成生产线编号
  form.value.lineCode = generateProductionLineCode();
  open.value = true;
  title.value = "添加生产线管理";
}

/** 修改按钮操作 */
/** 加载设备列表 */
// 修改这部分代码，移除重复声明
/** 加载设备列表 */

function handleEquipmentPagination(pagination) {
  equipmentQueryParams.value.pageNum = pagination.page;
  equipmentQueryParams.value.pageSize = pagination.limit;
  loadEquipmentList(form.value.lineId);
}

function loadEquipmentList(lineId) {
  equipmentLoading.value = true;
  const params = {
    pageNum: equipmentQueryParams.value.pageNum,
    pageSize: equipmentQueryParams.value.pageSize,
    lineId: lineId
  };
  
  listEquipment(params).then(res => {
    equipmentList.value = res.rows;
    equipmentTotal.value = res.total;
    equipmentLoading.value = false;
  }).catch(error => {
    console.error("加载设备列表失败:", error);
    equipmentLoading.value = false;
    proxy.$modal.msgError("加载设备列表失败");
  });
}

// function loadEquipmentList(lineId) {
//   equipmentLoading.value = true;
//   listEquipment({ lineId }).then(res => {
//     equipmentList.value = res.rows;
//     equipmentLoading.value = false;
//   }).catch(() => {
//     equipmentLoading.value = false;
//   });
// }

// 修改handleUpdate方法中的设备加载部分
function handleUpdate(row) {
  reset();
  const _lineId = row.lineId || ids.value;
  getLine(_lineId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改生产线管理";
    // 加载该生产线下的设备
    loadEquipmentList(_lineId);
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["lineRef"].validate(valid => {
    if (valid) {
      if (form.value.lineId != null) {
        updateLine(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addLine(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _lineIds = row.lineId || ids.value;
  proxy.$modal.confirm('是否确认删除生产线管理编号为"' + _lineIds + '"的数据项？').then(function() {
    return delLine(_lineIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('bdm/line/export', {
    ...queryParams.value
  }, `line_${new Date().getTime()}.xlsx`)
}

// 设备选择相关状态
const equipmentSelectOpen = ref(false);
const equipmentSelectLoading = ref(false);
const availableEquipmentList = ref([]);
const equipmentSelectTotal = ref(0);
const currentLineId = ref(null);

const equipmentSelectQueryParams = ref({
  pageNum: 1,
  pageSize: 10,
  equipmentName: null,
  equipmentCode: null,
  lineId: null
});

/** 添加设备按钮操作 */
function handleAddEquipment(row) {
  currentLineId.value = row.lineId;
  equipmentSelectOpen.value = true;
  getAvailableEquipmentList();
}

/** 获取可选设备列表 */
function getAvailableEquipmentList() {
  equipmentSelectLoading.value = true;
  // 查询参数，获取所有设备
  const params = {
    pageNum: equipmentSelectQueryParams.value.pageNum,
    pageSize: equipmentSelectQueryParams.value.pageSize,
    equipmentName: equipmentSelectQueryParams.value.equipmentName,
    equipmentCode: equipmentSelectQueryParams.value.equipmentCode
  };
  
  listEquipment(params).then(response => {
    // 显示所有设备，但已分配的设备会在界面上标记为"已分配"并禁用选择按钮
    availableEquipmentList.value = response.rows;
    equipmentSelectTotal.value = response.total;
    equipmentSelectLoading.value = false;
  }).catch(error => {
    console.error("获取设备列表失败:", error);
    equipmentSelectLoading.value = false;
    proxy.$modal.msgError("获取设备列表失败");
  });
}

/** 设备选择搜索按钮操作 */
function handleEquipmentSelectQuery() {
  equipmentSelectQueryParams.value.pageNum = 1;
  getAvailableEquipmentList();
}

/** 设备选择重置按钮操作 */
function resetEquipmentSelectQuery() {
  equipmentSelectQueryParams.value = {
    pageNum: 1,
    pageSize: 10,
    equipmentName: null,
    equipmentCode: null,
    lineId: null
  };
  getAvailableEquipmentList();
}

/** 确认添加设备 */
function confirmAddEquipment(row) {
  proxy.$modal.confirm('是否确认将该设备添加到当前生产线？').then(() => {
    // 更新设备的lineId
    const updateData = {
      equipmentId: row.equipmentId,
      lineId: currentLineId.value
    };
    
    updateEquipment(updateData).then(() => {
      proxy.$modal.msgSuccess("添加成功");
      equipmentSelectOpen.value = false;
      // 刷新设备列表
      loadEquipmentList(currentLineId.value);
    }).catch(error => {
      console.error("更新设备失败:", error);
      proxy.$modal.msgError("添加设备失败");
    });
  }).catch(() => {});
}

// 获取车间列表

// 在组件挂载时获取车间选项
onMounted(() => {
  // 获取车间列表
  listWorkshop().then(response => {
    workshopOptions.value = response.rows || response.data;
  });
  getList();
});

</script>

<style scoped>

</style>
